import http from '@/utils/http'
import {createAction} from "redux-actions";
// 导入 dayjs 相关包
import dayjs from 'dayjs';
// 导入本地格式化时间的插件
import localizedFormat from 'dayjs/plugin/localizedFormat';
import {
  ADDCOMMENT,
  SETARTICLEDETAIL,
  TOGGLELIKED,
  UPDATEARTICLEINFO,
  UPDATECOMMENTCOUNT,
  UPDATECOMMENTSRESULTS
} from "@/store/actionTypes";
import axios from "axios";


// 注册插件
dayjs.extend(localizedFormat);
const setArticleDetail = createAction(SETARTICLEDETAIL)
const updateArticleInfo = createAction(UPDATEARTICLEINFO)
const updateCommentResults = createAction(UPDATECOMMENTSRESULTS)
const addComment = createAction(ADDCOMMENT)
const toggleLiked = createAction(TOGGLELIKED)
export const updateCommentCount = createAction(UPDATECOMMENTCOUNT)

// 定义thunk函数，请求文章数据
export const getArticleById = id => async dispatch => {
  const res = await http.get(`/articles/${id}`);
  const detail = res.data
//  TODO: 写入redux
  dispatch(setArticleDetail({
    ...detail,
    // pubdate进行替换
    // 把时间进行格式化
    // 本地格式化：按照语言或者地区把时间格式化为适用于当前语言或者当前地区的时间格式
    pubdate: dayjs(detail.pubdate).locale('zh-cn').format('LL')
  }))

  return res.data

  // return Promise.reject('出错了厉害了')
}

export const followUser = (aut_id, is_followed) => async dispatch => {
  // 请求接口之前先进行判断
  if (is_followed) {
    //  取消关注
    await http.delete(`/user/followings/${aut_id}`)
  } else {
    await http.post("/user/followings", {
      target: aut_id
    })
  }
  // 通用
  dispatch(updateArticleInfo({
    name: 'is_followed', // 要更新的数据的key
    value: !is_followed,
  }))
}

export const collectArticle = (art_id, is_collected) => async dispatch => {
  if (is_collected) {
    //  取消收藏
    await http.delete(`article/collections/${art_id}`)
  } else {
    //  添加收藏
    await http.post('/article/collections', {
      target: art_id
    })
  }

  dispatch(updateArticleInfo({
    name: 'is_collected',
    value: !is_collected
  }))
}

// 点赞文章
export const likeArticle = (art_id, attitude) => async dispatch => {
  if (attitude === 1) {
    //  取消收藏
    await http.delete(`/article/likings/${art_id}`);
  } else {
    // 点赞
    await http.post('/article/likings', {
      target: art_id,
    });
  }

  dispatch(updateArticleInfo({
    name: 'attitude',
    value: attitude === 1 ? 0 : 1
  }))
}


/**
 * 首次获取数据的时候调用
 * @param {string} type 当前要获取评论类型 文章的评论/评论的回复
 * @param id
 */
export const getArticleComment = (type, id) => async dispatch => {
  const res = await http.get('/comments', {
    params: {
      type,
      source: id
    }
  })
  dispatch(updateCommentResults(res.data))
}

/**
 * 加载更多数据的时候 thunk
 * @param {String} type 获取的数据的类型
 * @param {string} art_id 文章的id或者评论的id
 * @param {string} offset 文章的偏移量,上一次返回数据的last_id
 * @return {(function(*): Promise<*>)|*}
 */
export const getMoreComments = (type, art_id, offset) => async dispatch => {
  const res = await http.get('/comments', {
    params: {
      type,
      source: art_id,
      offset
    }
  })
  dispatch(updateCommentResults(res.data))
}

export const addArticleComment = (art_id, content) => async dispatch => {
  const res = await http.post('/comments', {
    target: art_id,
    content
  })
  dispatch(addComment(res.data.new_obj))
}

export const likeComment = (id, is_liking) => async dispatch => {
//  is_liking为true 说明目前已经点赞了 ==> 取消点赞
//  没有点赞 is_liking为false， 去点赞
  if (is_liking) {
    //  取消点赞
    await http.delete(`comment/likings/${id}`)
  } else {
    //  去点赞
    await http.post('/comment/likings', {
      target: id,
    })
  }

  dispatch(toggleLiked({
    name: 'is_liking', // 要修改的字段名称
    value: !is_liking, // 需要修改成什么值
    target: id, // 要修改那条数据
    like_count: is_liking ? -1 : 1
  }))
}

